"""
CSPBuilder plugin

Provides workspace folders

Copyright (c) 2008 Rune M. Friborg, runef@diku.dk.
See LICENSE.txt for licensing details (GPLv2).
"""

PLUGIN_NAME = "Workspaces"

try:
    import cPickle as pickle
except:
    import pickle

import os
import wx

from plugins.builder import *


class PluginWorkspaces(PluginBUILDER):

    def __init__(self, pluginManager):
        PluginBUILDER.__init__(self, pluginManager, PLUGIN_NAME)

        self.home = os.getenv('USERPROFILE') or os.getenv('HOME')
        self.confPathAndFilename = self.home + '/.cspbuilder/builder.conf'

        self.folders = []
        self._load_pref()

        
        self.textCtrls = []

        
    def OnT1LeftDown(self, evt):
        evt.Skip()
        wx.CallAfter(self.CreateDirDialog, 0, evt)

    def OnT2LeftDown(self, evt):
        evt.Skip()
        wx.CallAfter(self.CreateDirDialog, 1, evt)

    def OnT3LeftDown(self, evt):
        evt.Skip()
        wx.CallAfter(self.CreateDirDialog, 2, evt)

    def OnT4LeftDown(self, evt):
        evt.Skip()
        wx.CallAfter(self.CreateDirDialog, 3, evt)

    def OnT5LeftDown(self, evt):
        evt.Skip()
        wx.CallAfter(self.CreateDirDialog, 4, evt)


    def CreateDirDialog(self, idx, evt):
        dlg = wx.DirDialog(None, "Choose a directory:",
                           style=wx.DD_DEFAULT_STYLE
                           #| wx.DD_DIR_MUST_EXIST
                           #| wx.DD_CHANGE_DIR
                           )
        try:
            dlg.SetPath(self.textCtrls[idx].GetValue())
        except:
            pass

        if dlg.ShowModal() == wx.ID_OK:
            try:
                self.textCtrls[idx].SetValue(dlg.GetPath())
            except:
                pass

        dlg.Destroy()


    def _startup(self, frame):
        
        if self.folders:
            return

        # No workspace folders! Run dialog

        # Introduction
        dlg = wx.MessageDialog(None, 'To be able to create and edit your own components you will need to create a workspace folder. Upon closing this dialog you will be presented with the option to add workspace folders. The configuration is saved in ~/.cspbuilder/builder.conf',
                               'New Installation - Setup Workspace Folder',
                               wx.OK
                               #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
                               )
        dlg.ShowModal()
        dlg.Destroy()

        self._prefmenu_activate(frame, None)


    def _prefmenu_activate(self, frame, event):
        
        dialog = wx.Dialog(frame, -1, "Configure workspace", style = wx.DEFAULT_FRAME_STYLE | wx.WANTS_CHARS )
        win = wx.Panel(dialog, -1)

        panelSizer = wx.BoxSizer(wx.VERTICAL)
        panelSizer.Add(wx.StaticText(win, -1, "Add workspace folders:"), 0, wx.ALL, 5)
        
        self.textCtrls = []

        for i in range(5):
            t = wx.TextCtrl(win, -1, '', size=(500, -1))
            panelSizer.Add(t, 0, wx.ALL, 5)
            if len(self.folders) > i:
                t.SetValue(self.folders[i])

            self.textCtrls.append(t)
        
        self.textCtrls[0].Bind(wx.EVT_LEFT_DOWN, self.OnT1LeftDown)
        self.textCtrls[1].Bind(wx.EVT_LEFT_DOWN, self.OnT2LeftDown)
        self.textCtrls[2].Bind(wx.EVT_LEFT_DOWN, self.OnT3LeftDown)
        self.textCtrls[3].Bind(wx.EVT_LEFT_DOWN, self.OnT4LeftDown)
        self.textCtrls[4].Bind(wx.EVT_LEFT_DOWN, self.OnT5LeftDown)

        btnOK = wx.Button(win, wx.ID_OK, " Ok ")
        panelSizer.Add(btnOK, 0, wx.ALL | wx.ALIGN_RIGHT, 5)

        win.SetSizer(panelSizer)
        win.SetAutoLayout(True)

        dialog.SetClientSize(wx.Size(520,250))

        if (dialog.ShowModal() == wx.ID_OK):
            self.folders = []
            for i in range(5):
                val = self.textCtrls[i].GetValue()
                if val != '':
                    self.folders.append(val)

        dialog.Destroy()

        self._save_pref()


    def _prefmenu(self, frame, menu, menuid):
        menu.Append(menuid, 'Configure Workspace Folders')
        frame.Bind(wx.EVT_MENU, lambda event:self._prefmenu_activate(frame,event), id=menuid)


    def __load_all_pref(self):

        D = {}
        if os.path.exists(self.confPathAndFilename):
            # Load
            f = open(self.confPathAndFilename, 'r')
            filedata = ''
            for line in f.readlines():
                filedata += line
            D = pickle.loads(filedata)
            f.close()
        else:
            self._create_empty_pref()

        return D

    def _save_pref(self):
        
        D = self.__load_all_pref()

        D['workspace'] = self.folders

        f = open(self.confPathAndFilename, "wb")
        f.write(pickle.dumps(D))
        f.close()
        
    def _load_pref(self):

        D = self.__load_all_pref()

        if (D.has_key('workspace')):
            self.folders = D['workspace']
        else:
            self.folders = []
                        
    def _create_empty_pref(self):
        
        if not os.path.exists(self.home + '/.cspbuilder'):
            os.mkdir(self.home + '/.cspbuilder')

        D = {}
        f = open(self.confPathAndFilename, "wb")
        f.write(pickle.dumps(D))
        f.close()


    def _getFolderList(self, L):
        # Todo: Create support for several folders.
        L = L + self.folders
        return L

    def _updatePath(self, L):
        # Put workspace folders between index 0 and tail.
        return [L[0]] + self.folders + L[1:]


def load(pluginManager):

    p = PluginWorkspaces(pluginManager)
    p.addToExecuteOnStartup(p._startup)
    p.addPrefMenuElement(p._prefmenu)
    p.addList(pathlist_COMPONENTS, p._getFolderList)
    p.addUpdatePath(p._updatePath)
    pluginManager.addPlugin(p)


